package Utils;/*
 *  @Author Mr.long
 *  @QQ 1507468405
 *  @Creat 2021/10/26 - 10:47
 */

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCTemp {
//    定义数据源对象
    private static DataSource ds;
    static{
        Properties pro = new Properties();
        try {
//        获取文件输入流对象，用于加载配置文件
            InputStream is = JDBCTemp.class.getClassLoader().getResourceAsStream("druid.properties");
            pro.load(is);
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
//    获取连接对象
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
    /*释放资源*/
    public static void close(Statement stmt, Connection conn) {
        close(null, stmt, conn);
    }

    public static void close(ResultSet rs, Statement stmt, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                //归还连接对象到数据连接池
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
//    返回数据源
    /*获取连接池对象
     * */
    public static DataSource getDataSource() {
    //        返回数据连接池对象
        return ds;
    }
}
